<template>
  <el-form
    :model="user"
    status-icon
    :rules="rules"
    ref="loginForm"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="userName">
      <el-input
        v-model="user.userName"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="pwd">
      <el-input
        type="password"
        v-model="user.pwd"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="doLogin">登录</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { userLogin } from '_api'
export default {
  name: 'Login',
  data () {
    return {
      user: {
        userName: '',
        pwd: ''
      },
      rules: {
        userName: [
          {
            required: true,
            message: '用户名必填'
          }
        ],
        pwd: [
          {
            required: true,
            message: '密码必填'
          }
        ]
      }
    }
  },
  methods: {
    doLogin () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 提交
          userLogin(this.user).then(res => {
            if (res.data.code === 200) {
              // 弹出成功提示
              this.$message({
                message: res.data.msg,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  const { token, userInfo, role } = res.data.data
                  // 缓存中备份一下 并存储到vuex中
                  localStorage.setItem('token', token)
                  localStorage.setItem('userInfo', JSON.stringify(userInfo))
                  localStorage.setItem('role', role)
                  // 存储到vuex中
                  this.$store.commit('user/INIT_USER_INFO', res.data.data)
                  // 跳转到首页
                  this.$router.replace('/dashBoard')
                }
              })
            }
          })
        } else {
          return false
        }
      })
    },
    resetForm () {
      this.$refs.loginForm.resetFields()
    }
  }
}
</script>
